import { defineStore } from 'pinia'
import router from '@/router/index.ts'
import { ElMessageBox, } from 'element-plus'

import { getToken, setToken, removeToken } from '@/utils/auth.ts'
import { isHttp, isEmpty } from "@/utils/validate.ts"
import defAva from '@/assets/images/profile.jpg'
import { API_LOGIN,LoginUserInfo } from '@/api/login.ts'


interface UserState {
  token: string | undefined;
  id: string;
  userName: string;
  nickName: string;
  avatar: string;
  roles: string[]; // 存的是roleKey数组
  permissions: string[]; // 明确 permissions 是字符串数组
}


const useUserStore = defineStore(
  'user',
  {
    state: (): UserState => ({
      token: getToken(),
      id: '',
      userName: '',
      nickName: '',
      avatar: '',
      roles: [],
      permissions: []
    }),

    getters:{
        getLoginUserId(state) {
          return state.id;
        }
    },
    actions: {
      // 登录,login.vue已经处理错误，而且API改造后返回的就是Promise
      // login(userInfo:LoginUserInfo) {
      //   return API_LOGIN.login(userInfo).then(res => {
      //       setToken(res.token)
      //       this.token = res.token
      //     })
        
      // },


      async login(userInfo: LoginUserInfo) {
        try {
          const res = await API_LOGIN.login(userInfo);
          setToken(res.token);
          this.token = res.token;
        } catch (error) {
          throw error; // 仍然传递给外部的 .catch()
        }
      },

      // 获取获取用户信息,这里改为异步，和ruoyi原来的return new Promise一样的效果，Store 负责管理状态和业务逻辑，API 层只负责网络请求
      async getInfo() { 
        const res = await API_LOGIN.getInfo()
        const user = res.user
        let avatar = user.avatar || ""
        if (!isHttp(avatar)) {
          avatar = (isEmpty(avatar)) ? defAva : import.meta.env.VITE_APP_BASE_API + avatar
        }
        if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          this.roles = res.roles
          this.permissions = res.permissions
          //console.log('请求getInfo', res.roles, res.permissions)
        } else {
          this.roles = ['ROLE_DEFAULT']
        }
        this.id = user.userId
        this.userName = user.userName
        this.nickName = user.nickName
        this.avatar = avatar
        /* 初始密码提示 */
        if (res.isDefaultModifyPwd) {
          ElMessageBox.confirm('您的密码还是初始密码，请修改密码！', '安全提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
            router.push({ name: 'Profile', params: { activeTab: 'resetPwd' } })
          }).catch(() => { })
        }
        /* 过期密码提示 */
        if (!res.isDefaultModifyPwd && res.isPasswordExpired) {
          ElMessageBox.confirm('您的密码已过期，请尽快修改密码！', '安全提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
            router.push({ name: 'Profile', params: { activeTab: 'resetPwd' } })
          }).catch(() => { })
        }

        
      },
      // 退出系统
      logOut() {
        return API_LOGIN.logout().then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
          })

      }
    }
  })

export default useUserStore
